from marajo.appengine.handlers.db import DBHandler
from marajo.appengine.api.users import User
from marajo.appengine.ext.db import Model, Key, Property
from marajo.exceptions import Unauthorized

from resources.project import Project
from resources.release import Release

import logging
log = logging.getLogger("vermouth.project_handler")

class ProjectHandler(DBHandler):
    """
    Override to only show projects this user is 
    a member of
    """

    def get_projects(self):
        if self.user.has_auth_group("employee"):
            query = Project.find()
        else:
            query = Project.find(members=self.user.key())
        return query

    def search(self, search_terms):
        """
        Search for given objects
        @param search_terms: The Terms to search for
        @type search_terms: MultiDict
        """
        objects = []
        query = self.get_projects()
        for filter in set(search_terms.keys()):
            filter_value = search_terms.getall(filter)
            if len(filter_value) == 1:
                filter_value = filter_value[0]
            if filter_value:
                query.filter("%s = " % filter, filter_value)
        for obj in query:
            objects.append(obj)
        return objects

    def create(self, params):
        if not self.user.has_auth_group("employee"):
            raise Unauthorized()
        else:
            return DBHandler.create(self, params)

    def update(self, obj, params):
        if not self.user.has_auth_group("employee"):
            raise Unauthorized()
        else:
            return DBHandler.update(self,obj, params)


    def edit_form(self, obj):
        properties = self.db_class.properties()
        d = {'properties' : properties,
            'action_method' : 'POST',
            'action_label' : 'Submit',
            'action_href' : "%s/%s" % (self.request.script_name, obj.id),
            'obj' : obj}
        d['users'] = User.all()
        self.display(self.edit_template, d)

